import pygame
import Image
from pygame.locals import *
import sys

import opencv
#this is important for capturing/displaying images
from opencv import highgui

from PIL import Image

camera = highgui.cvCreateCameraCapture(0)
help(camera)
def get_image():
    print 'Debug 1'
    im = highgui.cvQueryFrame(camera)
    # Add the line below if you need it (Ubuntu 8.04+)
    print 'Debug 2'
    im = opencv.cvGetMat(im)
    #convert Ipl image to PIL image
    print 'Debug 3'
    return opencv.adaptors.Ipl2PIL(im) 

fps = 30.0
pygame.init()
window = pygame.display.set_mode((640,480))
pygame.display.set_caption("WebCam Demo")
screen = pygame.display.get_surface()
print 'Before Loop'
while True:
    print 'Before event.get'
    events = pygame.event.get()
    print 'After event.get'
    for event in events:
        if event.type == QUIT or event.type == KEYDOWN:
            sys.exit(0)
    print 'After process event. Before get_image'
    im = get_image()
    print 'After get_image'
   
    help(im)
    string_representation = im.tostring()
    #print string_representation
    print 'string_representation made'
    #help(string_representation)
    im1 = Image.fromstring(im.mode,im.size,im.tostring())
    help(im1)
    pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)
    screen.blit(pg_img, (0,0))
    pygame.display.flip()
    pygame.time.delay(int(1000 * 1.0/fps))

